<template>
  <div class="p-6 bg-white rounded-lg shadow-md">
    <h2 class="text-2xl font-bold mb-6 text-gray-800">教学资源管理</h2>

    <el-form :inline="true" :model="searchForm" class="demo-form-inline mb-6 bg-gray-50 p-4 rounded-lg shadow-sm">
      <el-form-item label="资源名称" class="mb-0">
        <el-input v-model="searchForm.title" placeholder="请输入资源名称" clearable class="w-64"></el-input>
      </el-form-item>
      <el-form-item label="资源类型" class="mb-0">
        <el-select v-model="searchForm.resourceType" placeholder="请选择资源类型" clearable class="w-48">
          <el-option label="文档" value="文档"></el-option>
          <el-option label="课件" value="课件"></el-option>
          <el-option label="视频" value="视频"></el-option>
          <el-option label="图片" value="图片"></el-option>
          <el-option label="压缩包" value="压缩包"></el-option>
          <el-option label="Excel" value="Excel"></el-option>
          <el-option label="文本" value="文本"></el-option>
          <el-option label="音频" value="音频"></el-option>
          <el-option label="网页" value="网页"></el-option>
          <el-option label="代码" value="代码"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="mb-0">
        <el-button class="gradient-purple-blue-button" @click="handleSearch" ><el-icon><Search /></el-icon>查询</el-button>
        <el-button class="gradient-blue-cyan-button" @click="resetSearch" ><el-icon><RefreshLeft /></el-icon>重置</el-button>
        <el-button class="gradient-blue-toggle-button" @click="toggleView">
          {{ isCardView ? '切换为列表' : '切换为卡片' }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-upload
      class="upload-demo mb-6"
      drag
      :show-file-list="false"
      :http-request="handleUpload"
      multiple
      accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.mp4,.avi,.mov,.mp3,.wav,.zip,.rar,.txt,.html,.js,.css,.py,.java,.c,.cpp,.json"
    >
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div class="el-upload__text">将文件拖拽至此，或 <em>点击上传</em></div>
      <div class="el-upload__tip">支持多种格式在线预览（如 PDF, 图片, 视频），其他格式可能直接下载。</div>
    </el-upload>

    <el-divider class="my-6" />

    <div v-loading="loading">
      <template v-if="isCardView">
        <div class="resource-card-grid">
          <template v-if="resourceList.length > 0">
            <el-card v-for="resource in resourceList" :key="resource.id" class="resource-card rounded-lg shadow-md">
              <div class="card-content">
                <h3 class="card-title" :title="resource.title">{{ resource.title }}</h3>
                <p class="card-info">
                  <span class="info-label">类型:</span> {{ resource.resourceType }}
                </p>
                <p class="card-info">
                  <span class="info-label">上传时间:</span> {{ resource.uploadTime }}
                </p>
              </div>
              <div class="card-actions">
                <el-button
                  type="success"
                  size="small"
                  @click="handleDownload(resource)"
                >
                <el-icon><Download /></el-icon>下载
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(resource.id)"

                >
                <el-icon><Delete /></el-icon>删除
                </el-button>
              </div>
            </el-card>
          </template>
          <div v-else class="empty-resources">
            <el-empty description="暂无资源，请上传"></el-empty>
          </div>
        </div>
      </template>

      <template v-else>
        <el-table
          :data="resourceList"
          style="width: 100%"
          stripe
          border
          empty-text="暂无资源，请上传"
          class="rounded-lg overflow-hidden shadow-sm"
        >
          <el-table-column prop="title" label="资源名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="resourceType" label="类型" width="100" />
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                @click="handleDownload(scope.row)"
              >
              <el-icon><Download /></el-icon>下载
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.id)"

              >
              <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus';
import { UploadFilled, Download, Delete, Search, RefreshLeft  } from '@element-plus/icons-vue';
import courseService from '@/services/courseService.js';

const resourceList = ref([]);
const loading = ref(false);
const isCardView = ref(true); 

const searchForm = ref({
  courseId: null,
  title: '',
  resourceType: ''
});

// Function to toggle between card and table view
const toggleView = () => {
  isCardView.value = !isCardView.value;
};

// 👁 预览文件
const handlePreview = (resource) => {
  if (!resource || !resource.id) {
    ElMessage.warning('资源信息不完整，无法预览');
    return;
  }
  window.open(`/api/resources/download/${resource.id}?preview=true`, '_blank');
};

// ⬇ 下载文件
const handleDownload = async (resource) => {
  if (!resource || !resource.id) {
    ElMessage.warning('资源信息不完整，无法下载');
    return;
  }
  try {
    const response = await courseService.downloadCourseResource(resource.id);
    if (response.data) {
      const blob = new Blob([response.data], { type: response.headers['content-type'] });
      const url = window.URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.download = resource.title || resource.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      window.URL.revokeObjectURL(url);
    } else {
      ElMessage.error('下载文件失败：未收到文件数据');
    }
  } catch (err) {
    console.error('下载失败', err);
    ElMessage.error('下载失败');
  }
};

// 上传文件
const handleUpload = async (options) => {
  try {
    await courseService.uploadCourseResource(options.file);
    ElMessage.success('上传成功');
    await loadResources();
  } catch (e) {
    ElMessage.error('上传失败');
    console.error('上传失败详情:', e.response ? e.response.data : e.message);
  }
};

// 🗑 删除文件
const handleDelete = async (resourceId) => {
  try {
    await ElMessageBox.confirm('确定删除该资源吗？此操作不可逆！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await courseService.deleteCourseResource(resourceId);
    ElMessage.success('删除成功');
    await loadResources();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败详情:', error.response ? error.response.data : error.message);
    }
  }
};

// 处理查询
const handleSearch = () => {
  loadResources();
};

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    courseId: null,
    title: '',
    resourceType: ''
  };
  loadResources();
};

// ✅ ADDED: Helper function to format date from array
const formatDateArray = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray) || dateArray.length < 6) {
    return '时间无效';
  }
  const [year, month, day, hour, minute, second] = dateArray;
  // IMPORTANT: JavaScript's Date month is 0-indexed (0-11), so subtract 1
  const date = new Date(year, month - 1, day, hour, minute, second);
  
  if (isNaN(date.getTime())) {
    return '时间格式错误';
  }

  // Helper to pad numbers with a leading zero if they are less than 10
  const pad = (num) => String(num).padStart(2, '0');

  // Format to "YYYY-MM-DD HH:mm:ss"
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};


// ✅ MODIFIED: 加载资源列表
const loadResources = async () => {
  loading.value = true;
  try {
    const response = await courseService.getCourseResources(searchForm.value);
    
    // Map through the data and format the uploadTime for each resource
    const formattedData = response.data.map(resource => {
      return {
        ...resource,
        uploadTime: formatDateArray(resource.uploadTime)
      };
    });

    resourceList.value = formattedData;
    console.log("加载并格式化后的资源列表:", resourceList.value);
  } catch (e) {
    console.error('加载资源失败', e);
    ElMessage.error('加载资源失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadResources();
});
</script>

<style scoped>
/* Main container padding and background */
.p-6 {
  padding: 1.5rem;
}

.bg-white {
  background-color: #ffffff;
}

.rounded-lg {
  border-radius: 0.5rem;
}

.shadow-md {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

/* Header styling */
.text-2xl {
  font-size: 1.5rem;
  /* 24px */
}

.font-bold {
  font-weight: 700;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.text-gray-800 {
  color: #2d3748;
}

/* Search form styling */
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  /* Spacing between form items */
  align-items: center;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.p-4 {
  padding: 1rem;
}

.shadow-sm {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.w-64 {
  width: 16rem;
  /* 256px */
}

.w-48 {
  width: 12rem;
  /* 192px */
}

/* El-form-item specific overrides to remove default bottom margin */
.el-form-item.mb-0 {
  margin-bottom: 0 !important;
}

/* Upload component styling */
.upload-demo {
  /* 更明显的背景和边框 */
  background: linear-gradient(135deg, #f0f4f8 0%, #e0e7ed 100%);
  border: 2px dashed #a0aec0;
  border-radius: 12px;
  /* 略大圆角 */
  padding: 40px;
  /* 更多内边距 */
  text-align: center;
  margin-bottom: 2rem;
  /* 增加底部间距 */
  transition: all 0.4s ease;
  /* 更平滑过渡 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  /* 更明显的阴影 */
}

.upload-demo:hover {
  border-color: #6366f1;
  /* 悬停时更鲜艳的边框 */
  background: linear-gradient(135deg, #e0f0ff 0%, #cceeff 100%);
  /* 悬停时背景改为浅蓝色渐变 */
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
  /* 悬停时阴影更深 */
  transform: translateY(-3px);
  /* 悬停时轻微上浮 */
}

.el-icon--upload {
  font-size: 72px;
  /* 更大图标 */
  color: #9da9bb;
  /* 更深的图标颜色 */
  margin-bottom: 15px;
}

.el-upload__text {
  font-size: 18px;
  /* 字体更大 */
  color: #4a5568;
  /* 字体更深 */
}

.el-upload__text em {
  color: #4f46e5;
  /* 更鲜艳的“点击上传” */
  font-style: normal;
  font-weight: bold;
}

.el-upload__tip {
  font-size: 13px;
  /* 提示字体略大 */
  color: #718096;
  /* 提示字体更深 */
  margin-top: 10px;
}

/* Divider styling */
.el-divider.my-6 {
  margin-top: 2rem;
  /* 增加间距 */
  margin-bottom: 2rem;
  /* 增加间距 */
  height: 3px;
  /* 增粗 */
  background: linear-gradient(to right, #6366f1, #a855f7);
  /* 炫酷渐变色 */
  border: none;
  border-radius: 2px;
  /* 略圆角 */
  opacity: 0.8;
  /* 略微透明 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 增加阴影 */
}

/* Resource Card Grid and individual card styling */
.resource-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  /* 响应式网格布局 */
  gap: 20px;
  /* 卡片间距 */
  padding-bottom: 20px;
  /* 底部留白 */
}

.resource-card {
  background-color: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  /* 较圆的边角 */
  transition: all 0.3s ease;
  /* 平滑过渡 */
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  /* 柔和的阴影 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.resource-card:hover {
  transform: translateY(-5px);
  /* 悬停时上浮 */
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  /* 悬停时阴影加深 */
}

.card-content {
  padding: 20px;
  flex-grow: 1;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.info-label {
  font-weight: 600;
  color: #444;
  margin-right: 5px;
}

.card-actions {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  /* 按钮靠右 */
  gap: 10px;
  /* 按钮间距 */
}

.empty-resources {
  grid-column: 1 / -1;
  /* 让empty组件占据所有列 */
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  /* 确保有足够的高度显示 */
}

/* Table styling (restored for toggle functionality) */
.el-table {
  font-size: 15px;
  /* 字体略大 */
  border: 1px solid #e2e8f0;
  /* 明确的边框 */
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  /* 显著的阴影 */
}

.el-table th.el-table__cell {
  background: linear-gradient(to right, #4a5568, #2d3748);
  /* 深色渐变头部背景 */
  color: #ffffff;
  /* 头部文字白色 */
  font-weight: bold;
  padding: 15px 0;
  /* 增加头部内边距 */
  font-size: 16px;
  /* 头部字体更大 */
}

.el-table .el-table__cell {
  padding: 14px 0;
  /* 调整单元格内边距 */
}

/* 斑马纹效果 */
.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background-color: #f8f9fa;
  /* 更明显的浅灰色条纹 */
}

.el-table--striped .el-table__body tr.el-table__row td.el-table__cell {
  background-color: #ffffff;
  /* 白色条纹 */
}


/* --- Custom Button Styles (Gradient and Lighter) --- */

/* 查询按钮: 紫色到蓝色的渐变 (在现在的基础上深一点点) */
.gradient-purple-blue-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #8b5dbd, #548ee0) !important;
  /* 紫色到蓝色渐变 */
  border-color: #8b5dbd !important;
  /* 初始边框颜色 */
  transition: all 0.3s ease; /* Ensure transition is here */
}

.gradient-purple-blue-button:hover,
.gradient-purple-blue-button:focus {
  background-image: linear-gradient(to right, #9d70d1, #69a7f3) !important;
  /* 悬停时渐变颜色稍亮 */
  border-color: #9d70d1 !important;
  opacity: 0.9;
  transform: translateY(-2px); /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.gradient-purple-blue-button:active {
  background-image: linear-gradient(to right, #7b51aa, #4a7cc9) !important;
  /* 点击时渐变颜色稍深 */
  border-color: #7b51aa !important;
}

/* 重置按钮: 蓝色到青色的渐变  */
.gradient-blue-cyan-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #548ee0, #38afb5) !important;
  /* 蓝色到青色渐变 */
  border-color: #548ee0 !important;
  /* 初始边框颜色 */
  transition: all 0.3s ease; /* Ensure transition is here */
}

.gradient-blue-cyan-button:hover,
.gradient-blue-cyan-button:focus {
  background-image: linear-gradient(to right, #69a7f3, #4fd3d8) !important;
  /* 悬停时渐变颜色稍亮 */
  border-color: #69a7f3 !important;
  opacity: 0.9;
  transform: translateY(-2px); /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.gradient-blue-cyan-button:active {
  background-image: linear-gradient(to right, #4a7cc9, #2f969b) !important;
  /* 点击时渐变颜色稍深 */
  border-color: #4a7cc9 !important;
}

/* Toggle View button: A distinct blue-ish gradient for the toggle button */
.gradient-blue-toggle-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #3f51b5, #2196f3) !important; /* Indigo to Blue */
  border-color: #3f51b5 !important;
  transition: all 0.3s ease;
}

.gradient-blue-toggle-button:hover,
.gradient-blue-toggle-button:focus {
  background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important; /* Lighter shades on hover */
  border-color: #5c6bc0 !important;
  opacity: 0.9;
  transform: translateY(-2px); /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.gradient-blue-toggle-button:active {
  background-image: linear-gradient(to right, #303f9f, #1976d2) !important; /* Darker shades on active */
  border-color: #303f9f !important;
}


/* 下载按钮 (更浅的绿色，保持不变) */
.el-button--success {
  background-color: #e6f7ea !important;
  /* 浅绿色 */
  border-color: #c4e4cc !important;
  color: #34c759 !important;
  /* 保持文字颜色深一点以便阅读 */
}

.el-button--success:hover,
.el-button--success:focus {
  background-color: #d1eccd !important;
  border-color: #aed9b4 !important;
  color: #28a745 !important;
}

.el-button--success:active {
  background-color: #b8d4bb !important;
  border-color: #95c49d !important;
}


/* 删除按钮 (更浅的红色，保持不变) */
.el-button--danger {
  background-color: #fce7e9 !important;
  /* 浅红色 */
  border-color: #f7c9ce !important;
  color: #ea4d6a !important;
  /* 保持文字颜色深一点以便阅读 */
}

.el-button--danger:hover,
.el-button--danger:focus {
  background-color: #f7d1d5 !important;
  border-color: #f2a7af !important;
  color: #dc3545 !important;
}

.el-button--danger:active {
  background-color: #eeb8c0 !important;
  border-color: #e38d97 !important;
}
</style>